import React, { useCallback, useEffect, useRef, useState } from 'react';
import Editor, { OnMount, useMonaco } from '@monaco-editor/react';
import { Button, Modal } from 'antd';

type Props = {
  /** 是否展示*/
  isShow: boolean,
  /** 外部已经存在的类型 */
  alreadyExistType: {
    [key: string]: any
  },
  /** 完成*/
  handleOk: (data: any) => void,
  /** 取消*/
  handleCancel: () => void,
}

export default function OnlineEditing(props: Props) {
  const {
    alreadyExistType = {},
    isShow,
    handleOk,
    handleCancel
  } = props;

  const editorRef = useRef<any>(null);
  const monacoRef = useRef<any>(null);

  const onOk = useCallback(() => {
    let result = editorRef.current.getValue();
    handleOk(result)
  }, [handleOk])

  /** 添加自定义提示*/
  const addCustomPrompt = useCallback(() => {
    if (monacoRef.current === null) {
      return
    }

    Object.keys(alreadyExistType).forEach((key) => {
      const value = alreadyExistType[key];
      const libSource = `declare var ${key}: { 
        ${Object.keys(value).map((k) => `${k}: ${typeof value[k]}`).join(';')}
      };`;
      monacoRef.current.languages.typescript.javascriptDefaults.addExtraLib(libSource);
    });
  }, [alreadyExistType])

  const handleEditorDidMount = (editor: any, monaco: any) => {
    editorRef.current = editor;
    monacoRef.current = monaco;

    addCustomPrompt();
  };

  useEffect(() => {
    if (!isShow) {
      return;
    }
    addCustomPrompt();
  }, [alreadyExistType])

  return <>
    <Modal
      title="编辑器"
      width="60vw"
      open={isShow}
      onOk={onOk}
      onCancel={handleCancel}
    >
      <Editor
        height="60vh"
        defaultLanguage="javascript"
        defaultValue={`export default {${'\n\n'}}`}
        onMount={handleEditorDidMount}
      />
    </Modal>
  </>
}
